package com.cande.loki.exercise.algorithm;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @auther ROCK CODER
 * @DATE 2023/2/1 15:19
 * @Description 寻找子串在主串种出现的位置
 */
public class FindLastStr {
    public static void main(String[] args) {
        String str = "Hello avava, welcome to Java!";
        String subStr = "ava";

        int index = str.indexOf(subStr);
        while (index != -1) {
            System.out.println("子串 \"" + subStr + "\" 的起始位置: " + index);
            // 继续查找下一个出现的位置
            index = str.indexOf(subStr, index + 1);
        }

//        ---------------------------
//        String str = "abcabc";
//
//        System.out.println(str.lastIndexOf("c") );
//        System.out.println(      str.substring(2));
//
//        System.out.println(whereIsStr("afgdwafhh","af"));
        findMoreChar("asdsafasfqwdsadsadqwfsad");
    }

    /**
     * 寻找子串在主串种出现的位置
     * @param s
     * @param a
     * @return
     */
    public static String whereIsStr(String s,String a){
        String result="";
        int index = 0;
        if (!s.contains(a)){
            return result;
        }else {
            index= s.indexOf(a,index);
            result += index;
            while(s.substring(index+1).contains(a)){
                index= s.indexOf(a,index+1);
                result +=","+ index;
            }
            return result;
        }
    }

    /**
     * 出现最多的字符串
     * @param s
     */
    public static void findMoreChar(String s){
        String[] arr = s.split("");
        String resChar = "";
        Integer resNum = 0;
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        for (int i =0 ;i<arr.length;i++){
            if (map.containsKey(arr[i])){
                map.put(arr[i],map.get(arr[i]) +1);
            }else {
                map.put(arr[i], 1);
            }
            if (resNum<map.get(arr[i])){
                resNum = map.get(arr[i]);
                resChar = arr[i];
            }
        }
        System.out.println(resChar + "出现最多 次数为"+resNum);
    }

    /**
     * 查找最长不重复子串
     */
    public static String findMoreNoRepeatSubStr(String str){
        int start = 0, max = 0;
        int left = 0, right = 0;
        HashSet<Character> set = new HashSet<>();

        for (int i = 0; i < str.length(); i++) {
            if (set.contains(str.charAt(right))) {
                //包含 说明重复
                left++;
                set.remove(str.charAt(right));
            }else {
                //不包含说明没有 加进去
                right++;
                set.add(str.charAt(right));

                //这是关键 要设置start和最大长度
                if (right-left >max) {
                    max = right-left;
                    start = left;
                }
            }
        }

        return str.substring(start, start+max);
    }

}
